package com.blog.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.blog.annotation.DataDict;
import com.blog.common.CommonRespDto;
import com.blog.service.SysDictionaryItemService;
import com.blog.utils.BeanUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 定义切面类
 */
@Aspect
@Component
public class AopDictAspect {

    private Logger log = LoggerFactory.getLogger(AopDictAspect.class);


    @Autowired
    SysDictionaryItemService sysDictionaryItemBizService;

    /**
     * 定义切入点
     *      @Pointcut：标注在方法上，用来定义切入点
     */
    @Pointcut("execution(* com.blog.controller..*.*(..))")
    public void execute(){

    }

    @Around("execute()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object result = point.proceed();
        translateDict(result);
        return result;
    }

    /**
     * 翻译字典
     * @param result
     */
    private void translateDict(Object result) {
        if (result instanceof CommonRespDto ){
            //封装返回的值
            List<JSONObject> items = new ArrayList<>();
            //将获取对象强制转化成Result对象
            CommonRespDto dictResult = (CommonRespDto)result;
            //获取的Result获取getData()转化成list
            List<?> list =null;
            /*if(dictResult.getData() instanceof IPage){
                list = ((IPage) dictResult.getData()).getRecords();
            }else */
            if(dictResult.getData() instanceof List){
                list = (List<?>)dictResult.getData();
            }else {
                //不翻译
                return;
            }
            //循环list获取里面注册标注的数据添加值
            for (Object o : list) {
                //获取值进行json格式的转化
                ObjectMapper mapper = new ObjectMapper();
                String json = "{}";
                try {
                    json=mapper.writeValueAsString(o);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }

                JSONObject parseObject = JSON.parseObject(json);
                //遍历获取对象中的属性和名称
                for (Field field : BeanUtil.getAllFields(o)) {
                    //获取注解标注的值
                    if (field.getAnnotation(DataDict.class)!=null){
                        String dictDataSource = field.getAnnotation(DataDict.class).dictDataSource();
                        String dictText = field.getAnnotation(DataDict.class).dictText();
                        //获取当前key值
                        String keys = String.valueOf(parseObject.get(field.getName()));
                        //获取当前字典中的值
                        String textValue = translateTextValue(dictDataSource,keys);
                        if (StringUtils.isNotBlank(dictText)){
                            parseObject.put(dictText,textValue);
                        }else {
                            parseObject.put(field.getName()+"Text",textValue);
                        }
                    }
                }
                items.add(parseObject);
            }
            /*if(dictResult.getData() instanceof IPage){
                ((IPage) dictResult.getData()).setRecords(items);
            }else */
            if(dictResult.getData() instanceof List){
                dictResult.setData(items);
            }
        }
    }

    /**
     * 获取字典中的值
     * @param dictCode 字典编码
     * @param itemCodes 字典子项编码
     * @return
     */
    private String translateTextValue(String dictCode, String itemCodes) {
        if (StringUtils.isBlank(dictCode) || StringUtils.isBlank(itemCodes)){
            return null;
        }
        StringBuffer buffer = new StringBuffer();

        //分割key将分割的key循环便利进行查询
        String[] itemCodeList = itemCodes.split(",");
        for (String itemCode : itemCodeList) {
            String itemValue =null;
            if (itemCode.trim().length()==0){
                continue;
            }
            log.info("字典子项编码:{}",itemCode);
            itemValue = sysDictionaryItemBizService.selectByDictCodeAndItemCode(dictCode,itemCode);

            if (StringUtils.isNotBlank(itemValue)){
                if (!"".equals(buffer.toString())){
                    buffer.append(",");
                }
                buffer.append(itemValue);
            }
        }
        return buffer.toString();
    }
}
